package com.gykj.sso.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gykj.sso.config.SSOProperties;
import com.gykj.sso.config.StateEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.util.Optional;

@Slf4j
public class SSOInterceptor implements HandlerInterceptor {
    private final SSOProperties ssoProperties;
    public SSOInterceptor(SSOProperties ssoProperties){
        this.ssoProperties = ssoProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String ip = InetAddress.getLocalHost().getHostAddress();

        // 必定放行
        if (request.getRequestURI().contains("."))  return true;// 放行静态资源 可完善为具体的后缀
        if (request.getRequestURI().contains("mock")) return true;// 放行 mock
        if ("/403".equals(request.getRequestURI())) return true;


        String debug = Optional.ofNullable(ssoProperties.getDebug()).orElse("false");// 默认关闭
        if(Boolean.parseBoolean(debug)){// debug
            request.getSession().setAttribute("username", "420923200108033954");// 测试者身份证号
            return true;
        }else{

        }

        String redirectUri = request.getRequestURI();
        String state = StateEntity.getState();
        StateEntity.setState(state, redirectUri);

        String responseType = Optional.ofNullable(ssoProperties.getResponseType()).orElse("");// 默认空
        String clientId = Optional.ofNullable(ssoProperties.getClientId()).orElse("");// 默认空
        String serverUrl = Optional.ofNullable(ssoProperties.getServerUrl()).orElse("");// 默认空
        String loginUrl = serverUrl + Optional.ofNullable(ssoProperties.getLoginUrl()).orElse("");// 默认空

        String resultUrl = String.format("%s%s?response_type=%s&client_id=%s&redirect_uri=%s&state=%S", serverUrl, loginUrl, responseType, clientId, redirectUri, state);

        HttpSession session = request.getSession();
        String login = request.getContextPath() + "/sys/ssoLogin";
        JSONObject oauthData = (JSONObject) session.getAttribute("oauthData");
        //未登录
        if (oauthData == null) {
            log.info("用户未登录");

            //不是登录登录，跳转到登录页面
            if (!login.equals(request.getRequestURI())) {
                log.info("跳转到登录页面，{}", resultUrl);
                response.sendRedirect(resultUrl);
            }
        }else {
            //todo 权限验证

            // 如果是登录请求，直接跳转到主页
            if (login.equals(request.getRequestURI())) {
                log.info("用户已登录,跳转到主页");
                response.sendRedirect(request.getContextPath() + "/index");
            }
        }
        return true;
    }
}
